package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.controller.grid.helper.GridHelper;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridNoticeDto;
import com.quectel.core.module.grid.dto.GridNoticeRelationDto;
import com.quectel.core.module.grid.dto.GridRegionInfoDto;
import com.quectel.core.module.grid.service.GridNoticeRelationService;
import com.quectel.core.module.grid.service.GridNoticeService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@RestController
@RequestMapping("gridNoticeRelation")
@Tag(name = "GridNoticeRelationController", description = "网格公告发布范围关系表相关api")
public class GridNoticeRelationController extends BaseController {


    @DubboReference
    private GridNoticeService gridNoticeService;
    @DubboReference
    private GridNoticeRelationService gridNoticeRelationService;
    @Autowired
    private GridHelper gridHelper;

    /**
     * 上级通知列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("parentList")
    @RequirePermissions(values = "gridNoticeRelation:list")
    @Operation(summary = "上级通知列表")
    public Response<Page<GridNoticeRelationDto>> parentList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        //查询当前用户组级别
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(SessionHolder.getSysUser().getGroupId());

        if (CollectionUtils.isEmpty(gridRegionInfoDtos)) {
            Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
        }

        //判断该级是否有上级通知
        Boolean aBoolean = gridHelper.checkIfExistSuperiorNotice(gridRegionInfoDtos);
        if (Boolean.FALSE.equals(aBoolean)) {
            Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
        }

        List<String> sourceIds = gridRegionInfoDtos.stream().map(GridRegionInfoDto::getCode).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sourceIds)) {
            request.put(LambdaUtil.getFieldName(GridNoticeRelationDto::getSourceType), gridRegionInfoDtos.get(0).getLevel());
            request.put(GridConstant.SOURCE_IDS, sourceIds);
        }
        //筛选启用状态
        request.put(LambdaUtil.getFieldName(GridNoticeDto::getStatus), SystemConstants.COMMON);

        int total = gridNoticeRelationService.queryTotal(request.getParams());

        List<GridNoticeRelationDto> list = null;
        if (total > 0) {
            list = gridNoticeRelationService.queryList(request.getParams());
            list.forEach(gridNoticeRelationDto -> {
                gridNoticeRelationDto.setGridNotice(gridNoticeService.selectById(gridNoticeRelationDto.getGridNoticeId()));
            });
        } else {
            list = new ArrayList<>();
        }

        Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
    }


    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridNoticeRelation:list")
    @Operation(summary = "网格公告发布范围的分页查询列表")
    public Response<Page<GridNoticeRelationDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridNoticeRelationService.queryTotal(request.getParams());

        List<GridNoticeRelationDto> list = null;
        if (total > 0) {
            list = gridNoticeRelationService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridNoticeRelation:edit")
    @Operation(summary = "查询单条网格公告发布范围记录")
    public Response<GridNoticeRelationDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        //筛选启用状态
        params.put(LambdaUtil.getFieldName(GridNoticeDto::getStatus), SystemConstants.COMMON);
        if (gridNoticeRelationService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeRelationDto gridNoticeRelationDto = gridNoticeRelationService.selectById(id);

        GridNoticeDto noticeDto = gridNoticeService.selectById(gridNoticeRelationDto.getGridNoticeId());
        gridNoticeRelationDto.setGridNotice(noticeDto);

        return Response.<GridNoticeRelationDto>ok().wrap(gridNoticeRelationDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridNoticeRelation:info")
    @Operation(summary = "查询单条网格公告发布范围记录")
    public Response<GridNoticeRelationDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        //筛选启用状态
        params.put(LambdaUtil.getFieldName(GridNoticeDto::getStatus), SystemConstants.COMMON);
        if (gridNoticeRelationService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeRelationDto gridNoticeRelationDto = gridNoticeRelationService.selectById(id);
        GridNoticeDto noticeDto = gridNoticeService.selectById(gridNoticeRelationDto.getGridNoticeId());
        gridNoticeRelationDto.setGridNotice(noticeDto);

        //更新已读状态
        if (SystemConstants.NO.equals(gridNoticeRelationDto.getReadStatus())) {
            gridNoticeRelationDto.setReadStatus(SystemConstants.YES);
            gridNoticeRelationService.updateById(gridNoticeRelationDto);
        }

        return Response.<GridNoticeRelationDto>ok().wrap(gridNoticeRelationDto);
    }

    /**
     * 保存
     *
     * @param gridNoticeRelationDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridNoticeRelation:edit")
    @Operation(summary = "保存单条网格公告发布范围记录")
    public Response<Object> save(@RequestBody @Validated GridNoticeRelationDto gridNoticeRelationDto) {

        //填充基础数据
        fillSaveCommonData(gridNoticeRelationDto);

        gridNoticeRelationService.save(gridNoticeRelationDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridNoticeRelationDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridNoticeRelation:edit")
    @Operation(summary = "修改单条网格公告发布范围记录")
    public Response<Object> update(@RequestBody @Validated GridNoticeRelationDto gridNoticeRelationDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridNoticeRelationDto.getId()));
        if (gridNoticeRelationService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(gridNoticeRelationDto);

        gridNoticeRelationService.updateById(gridNoticeRelationDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridNoticeRelation:delete")
    @Operation(summary = "批量删除存在的网格公告发布范围记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridNoticeRelationService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridNoticeRelationService.deleteBatch(ids);

        return Response.ok();
    }
}
